/**
 * User: hou wanchun
 * Date: Mar 20, 2003
 * Time: 10:40:17 AM
 */
package com.ecomm.util.dbadapter;

import com.ecomm.exception.DBException;
import com.ecomm.util.Config;
import com.ecomm.util.DAO;
import com.ecomm.util.Logger;
import org.apache.commons.logging.Log;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Properties;

/**
 * 使用JNDI连接池的DAO
 * 使用配置文件database.jndi部分的信息初始化
 * 配置文件的参考例子：
 */

public class JndiDAO implements DAO
{
    private static Log log = Logger.getLog(JndiDAO.class);

    private static String jndiname = null;
    private static String jndifactory = null;
    private static String jndiprovider = null;

    static
    {
        jndiname = Config.getString("database.jndi.jndiname");
        jndifactory = Config.getString("database.jndi.initial_context_factory");
        jndiprovider = Config.getString("database.jndi.contextProviderURL");
    }

    /**
     * 取得一个数据库连接
     *
     * @return
     * @throws DBException
     */
    public Connection getConnection() throws DBException
    {
        InitialContext initCtx = null;
        try
        {
            if (jndifactory == null || jndiprovider == null)
            {
                initCtx = new InitialContext();
                DataSource ds = (DataSource) initCtx.lookup(jndiname);
                return ds.getConnection();
            }
            else
            {
                Properties p = new Properties();
                p.put(Context.INITIAL_CONTEXT_FACTORY, jndifactory);
                p.put(Context.PROVIDER_URL, jndiprovider);
                initCtx = new InitialContext(p);
                DataSource ds = (DataSource) initCtx.lookup(jndiname);
                return ds.getConnection();
            }
        }
        catch (Exception e)
        {
            log.error("不能取得一个jndi的数据库连接", e);
            throw new DBException("不能取得一个jndi的数据库连接");
        }
    }
}
